Skip to content

Bound dashboard runtime events before RPC serialization - #452

Merged
m-aebrer merged 6 commits into
masterfrom
feature/issue-448-bound-rpc-runtime-events
Aug 11, 2026
Merged

m-aebrer merged 6 commits into
masterfrom
feature/issue-448-bound-rpc-runtime-events

Conversation

@m-aebrer

Copy link
Copy Markdown
Collaborator

Closes #448

High-rate model events carry cumulative assistant state (message, assistantMessageEvent.partial) across the internal dreb-child RPC JSONL pipe before the dashboard's EventHub projection runs, causing quadratic serialization and unbounded stdout queuing (observed: 6,401 events in a 3-second end-of-response burst). This PR projects dashboard-specific streaming events before RPC JSONL serialization (gated on --ui dashboard) and makes the child stdout queue explicitly bounded with backpressure handling.

Implementation plan posted as a comment below.

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Implementation Plan

Problem analysis

The quadratic pipe cost is fully mapped from code evidence:

  1. packages/agent/src/agent-loop.ts emits message_update with two cumulative copies: message: {...partialMessage} and assistantMessageEvent.partial (every AssistantMessageEvent variant in packages/ai/src/types.ts carries a full growing partial: AssistantMessage)
  2. packages/coding-agent/src/modes/rpc/rpc-mode.ts — the session.subscribe((event) => output(event)) callback serializes events verbatim via serializeJsonLine → writeRawStdout, producing O(n²) aggregate bytes on the child→dashboard JSONL pipe for a response of n tokens
  3. packages/coding-agent/src/core/output-guard.ts — writeRawStdout() discards the stream.write() backpressure boolean; there is no queue and no drain handling, so a stalled pipe means unbounded in-memory queuing inside the child — the mechanism behind the observed 6,401-event / 3-second end-of-response burst
  4. packages/dashboard/src/server/event-hub.ts — projectDashboardEvent (merged in PR 447) strips these fields, but only after the pipe, at the browser SSE boundary. The quadratic serialization and queuing happen before that protection can apply.

Stripping is safe (verified against all consumers):

  • The dashboard browser reducer (packages/dashboard/src/client/state/reducer.ts) reads only type/delta/content from assistantMessageEvent — never event.message or partial
  • RuntimePool.handleEvent reads message only from message_end (provider-error detection) — never from message_update
  • Authoritative finalization flows through message_end.message, and full recovery flows through the get_dashboard_snapshot RPC response — neither is touched
  • The dashboard is the only consumer that launches a child with --ui dashboard (packages/dashboard/src/server/runtime-pool.ts spawn args)

Deliverables

1. Dashboard-mode projection before serialization (coding-agent)

  • New module packages/coding-agent/src/modes/rpc/rpc-event-projection.ts exporting a pure projection function that:
    • strips top-level message from message_update and partial from its nested assistantMessageEvent, preserving type, contentIndex, delta, content, and toolCall
    • recurses into background_agent_event nested payloads (acceptance criterion: nested background-agent events covered)
    • passes every other event type through unchanged; never mutates its input
    • Note: this helper must live in coding-agent — @dreb/dashboard depends on @dreb/coding-agent, so importing the dashboard's projectDashboardEvent would be a circular dependency. EventHub keeps its broader projection (images, retries, tool_execution_update.args, agent_end.messages) as an intentional second boundary.
  • Gated on uiType === "dashboard": expose the currently-private AgentSession._uiType via a public readonly getter
  • Applied in the session.subscribe callback in runRpcMode — not in output(), so RPC command responses (especially get_dashboard_snapshot's full transcript) are never projected
  • Non-dashboard RPC consumers (default --ui rpc, --ui agent, print/JSON modes): zero protocol change

2. Bounded stdout backpressure (output-guard.ts)

  • writeRawStdout respects the stream.write() boolean: when it returns false, subsequent writes queue and flush in write order on drain
  • The queue is byte-capped (constant, ~16 MiB, documented); exceeding the cap fails loudly — explicit stderr diagnostic plus nonzero process exit. Rationale: a child whose stdout pipe is permanently stalled is unusable, and the dashboard already surfaces child exit as a runtime error. No silent drops, no unbounded growth (per dreb's loud-failure convention).
  • Synchronous call-site signature unchanged; print-mode call sites benefit identically

3. Regression tests (mandatory, not deferred)

  • packages/coding-agent/test/rpc-event-projection.test.ts (new): pure projection unit tests — strips cumulative fields, preserves delta fields, recurses background_agent_event, identity passthrough for other event types, input immutability
  • New RPC-mode streaming regression test (new file, reusing the dispatchRpcCommand / writeRawStdout-spy harness pattern from test/rpc-dashboard-commands.test.ts and the 2,000-event storm fixture pattern from packages/dashboard/test/event-hub.test.ts): drive the runRpcMode subscribe path with ~2,000 synthetic growing message_update events in dashboard mode and assert:
    • every captured stdout frame is below a small byte bound
    • aggregate serialized bytes grow ~linearly in N (explicitly not quadratic — compare N vs 2N totals)
    • message/partial are absent while deltas survive
    • get_dashboard_snapshot responses remain unprojected
    • repeat with uiType: "rpc" asserting full passthrough (generic protocol compatibility)
  • packages/coding-agent/test/output-guard.test.ts (new, modeled on test/stderr-guard.test.ts — output-guard currently has zero unit tests): takeover/restore/isStdoutTakenOver, direct write, backpressure queue with in-order drain flush, loud failure at the byte cap. Constructor mocks use the function keyword per vitest v4 convention.
  • Dashboard package: no changes expected; existing EventHub storm tests remain valid because the projected wire shape is identical to what EventHub already produces

4. Documentation

  • packages/coding-agent/docs/rpc.md: document that with --ui dashboard, message_update omits the cumulative message and assistantMessageEvent.partial fields before serialization (including inside background_agent_event), while the generic RPC protocol is unchanged. The sections describing message_update streaming payloads and the background_agent_event verbatim relay both need the note.
  • Root README.md and packages/coding-agent/README.md: verify whether they describe RPC streaming payload shapes; update only if they mention these cumulative fields

Files to create or modify

File Change
packages/coding-agent/src/modes/rpc/rpc-event-projection.ts New projection module
packages/coding-agent/src/modes/rpc/rpc-mode.ts Apply projection in the subscribe callback, dashboard mode only
packages/coding-agent/src/core/agent-session.ts Public readonly uiType getter
packages/coding-agent/src/core/output-guard.ts Backpressure queue + loud byte cap
packages/coding-agent/test/rpc-event-projection.test.ts New unit tests
packages/coding-agent/test/rpc-mode-streaming.test.ts (name TBD) New high-rate regression test
packages/coding-agent/test/output-guard.test.ts New unit tests
packages/coding-agent/docs/rpc.md Document dashboard-mode wire projection

Acceptance criteria mapping

Issue criterion Covered by
Dashboard-mode message_update strips message + assistantMessageEvent.partial before JSONL serialization, incl. nested background-agent events Deliverable 1 + projection unit tests
Deltas, finalized content/tool calls, transcript behavior, authoritative recovery remain correct message_end and get_dashboard_snapshot untouched; delta-preservation and snapshot-passthrough test assertions
Long high-rate regression proves bounded records, near-linear aggregate bytes, bounded stdout queuing Deliverable 3 streaming regression + output-guard tests
Non-dashboard RPC consumers retain existing protocol behavior uiType === "dashboard" gate + uiType: "rpc" passthrough test

Risks and open questions

  • Loud-failure mechanism at the stdout cap: explicit stderr diagnostic + process.exit(1) from the drain path (an async context where throwing is uncatchable) is the recommended shape; implementation will confirm the cleanest propagation point
  • Cap value: ~16 MiB constant, documented alongside the code (EventHub's browser buffer is 8 MiB; the child queue should comfortably exceed steady-state projected flow without hiding a real stall)
  • Scope discipline: only the two quadratic fields are projected pre-serialization; broadening pre-serialization stripping to agent_end.messages, retry discardedPartial, etc. stays an EventHub-boundary concern and is out of scope here

Plan created by mach6

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Vitest coverage

Metric Covered Total Coverage
Statements 39133 55321 70.73%
Branches 20894 34507 60.55%
Functions 8280 11566 71.58%
Lines 28267 39763 71.08%

View full coverage run

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Progress Update

Implementation of the plan is complete and verified.

Changes:

  • src/modes/rpc/rpc-event-projection.ts (new) — pure projection that strips the cumulative top-level message and nested assistantMessageEvent.partial from message_update frames, recurses into background_agent_event payloads, never mutates inputs, and passes unknown event types through by reference (forward-safe)
  • src/modes/rpc/rpc-mode.ts — the session.subscribe output path applies the projection only when session.uiType === "dashboard"; command responses (including get_dashboard_snapshot) are never projected, and generic RPC consumers see the unchanged full protocol
  • src/core/agent-session.ts — public readonly uiType getter exposing the --ui flag / mode default
  • src/core/output-guard.ts — writeRawStdout now honors the stream.write() backpressure boolean: writes queue in order while backpressured and flush on drain; the queue is byte-capped at 16 MiB and exceeding the cap fails loudly (stderr diagnostic + exit 1) instead of growing memory unboundedly; flushRawStdout waits for queued output to drain
  • docs/rpc.md — documents the dashboard-mode wire projection, including the recursive behavior for relayed background-agent events

Tests (24 new, all passing):

  • test/rpc-event-projection.test.ts — 9 unit tests: field stripping, delta preservation, background-event recursion, input immutability, identity passthrough, bounded frame size vs cumulative size
  • test/rpc-mode-dashboard-projection.test.ts — 4 regression tests driving runRpcMode with the faux streaming harness: thousands of message_update frames all bounded under 512 bytes per delta frame, aggregate message_update bytes near-linear in response length (doubling the response less-than-2.5x'es the bytes; the unprojected shape would quadruple them), get_dashboard_snapshot responses unprojected, and full cumulative passthrough when uiType is not dashboard
  • test/output-guard.test.ts — 11 unit tests (output-guard previously had none): takeover routing/idempotence/restore, direct write, interception bypass, ordered drain flush, no duplication of the false-return chunk, re-backpressure mid-flush, loud failure at the byte cap, and flushRawStdout drain waiting

Verification: full monorepo build clean; full test suite green (4,930 passed, 0 failed); workspace links healthy; biome clean. Live binary QA on the built CLI: with --ui dashboard a streamed prompt produced 4 message_update frames with zero cumulative message/partial fields and an intact authoritative message_end; without the flag, all 216 message_update frames retained both cumulative fields exactly as before.

Commit: 57caa1c


Progress tracked by mach6

@m-aebrer
m-aebrer marked this pull request as ready for review August 11, 2026 19:00
@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Code Review

Critical

None.

Important

None.

Suggestions

  1. Add an RPC-boundary regression for nested background-agent updates (packages/coding-agent/test/rpc-mode-dashboard-projection.test.ts, confidence 93). The pure projection unit test covers recursion, but the runRpcMode serialization tests only stream top-level message_update frames. Exercise a background_agent_event containing a growing message_update and assert the serialized dashboard frame omits nested message and assistantMessageEvent.partial, retains deltas, and stays bounded.

  2. Test backpressure through the stdout-takeover route used by RPC mode (packages/coding-agent/test/output-guard.test.ts, confidence 88). Queue/drain/cap tests currently cover the direct process.stdout.write route, while RPC writes use stdoutTakeoverState.rawStdoutWrite. Add a takeover-path test whose raw writer returns false, then verify ordered, nonduplicated delivery after drain and cap behavior.

  3. Guarantee the cap-overflow diagnostic is flushed before exiting (packages/coding-agent/src/core/output-guard.ts, confidence 80). The cap path calls process.stderr.write(...) immediately followed by process.exit(1). Because the dashboard child has piped asynchronous stderr, Node may terminate before the diagnostic is delivered. The nonzero exit remains visible, but the reason can disappear; exit from the write callback or otherwise ensure bounded diagnostic delivery.

Strengths

  • Dashboard projection is narrowly scoped, immutable, recursively handles background-agent events, and leaves authoritative final/snapshot paths untouched.
  • The dashboard-only gate preserves generic RPC compatibility.
  • The stdout queue preserves ordering, handles repeated backpressure, has a documented byte cap, and avoids duplicate chunks.
  • Existing tests substantively cover bounded top-level frames, near-linear aggregate bytes, snapshot passthrough, generic RPC passthrough, helper recursion, and queue/drain behavior.
  • The implementation fully maps to issue 448 and the approved plan; no simplification concerns were found.

Agents run: code-reviewer, error-auditor, test-reviewer, completeness-checker, simplifier


Reviewed by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Review Assessment

Review comment

Classifications

Finding Classification Reasoning
1. Missing RPC-boundary test for nested background-agent updates nitpick Factual: The exact nested behavior lacks a second end-to-end assertion, but the pure helper test directly proves recursive projection and the integration test proves that same helper is unconditionally applied to every subscribed dashboard event before serialization. Scope: The composition already establishes the acceptance behavior; another integration case would be redundant rather than necessary for safe delivery.
2. Backpressure not tested through stdout takeover genuine Factual: All queue/drain/cap tests use the direct process.stdout.write branch. The takeover branch using stdoutTakeoverState.rawStdoutWrite—the production RPC path—is only tested for a successful non-backpressured write. Scope: Bounded child stdout behavior is an explicit acceptance criterion and newly introduced behavior; the takeover-routing and drain-listener composition on the actual RPC path must be covered.
3. Cap diagnostic may be truncated before exit genuine Factual: With piped asynchronous stderr, process.stderr.write(...) immediately followed by process.exit(1) can terminate before the diagnostic is delivered. Scope: The approved deliverable explicitly requires an stderr diagnostic plus nonzero exit and calls for confirming a clean propagation mechanism. Losing the reason violates the scoped loud-failure requirement.

Action Plan

  1. Add an output-guard test that enters stdout takeover, drives backpressure and queued writes through rawStdoutWrite, emits drain, and verifies ordered, nonduplicated delivery and cap behavior.
  2. Make cap-overflow termination wait for stderr write completion, with a bounded forced-exit fallback so a stalled stderr pipe cannot hang the child.

Assessment by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Progress Update

Addressed genuine review findings 2 and 3:

  • Added regression coverage for stdout backpressure through the takeover/raw-writer route used by RPC mode, including ordered drain flushing and queue-cap behavior.
  • Changed queue-cap termination to wait for the fatal stderr diagnostic to flush before exiting.
  • Added a one-second unref'd forced-exit fallback so a permanently stalled stderr pipe cannot hang the child.
  • Added regression coverage for both successful diagnostic flushing and the bounded fallback.

Verification passed: focused output-guard tests, full test suite, Biome, full monorepo build, workspace-link verification, and diff checks.

Commit: 2dae4ff


Progress tracked by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Code Review

Critical

None.

Important

None.

Suggestions

  1. A single large unprojected response can exceed the stdout queue cap during ordinary backpressure (packages/coding-agent/src/core/output-guard.ts, confidence 82, medium). Command responses such as get_dashboard_snapshot intentionally retain the complete transcript. If stdout is already backpressured, one legitimate response near or above the 16 MiB cap is enqueued and causes a fatal exit even when the reader is healthy and only temporarily stalled. Consider distinguishing a single oversized frame from accumulated backlog or otherwise sizing the policy for complete snapshot responses.

  2. flushRawStdout can wait indefinitely when a below-cap queue never drains (packages/coding-agent/src/core/output-guard.ts, confidence 80, low). Drain waiters resolve only from flushStdoutQueue; if the consumer stalls after writes stop, no further cap check occurs and the promise has no timeout. Consider a bounded loud-failure path for flush waits.

Strengths

  • Dashboard projection is narrowly gated, immutable, recursively handles background-agent events, and leaves authoritative final/snapshot paths untouched.
  • Generic RPC compatibility is preserved.
  • Queue ordering, repeated backpressure, takeover routing, nonduplication, cap diagnostics, and forced-exit behavior are well tested.
  • Tests cover bounded frames, near-linear aggregate bytes, complete snapshots/finals, and non-dashboard passthrough.
  • All issue and plan requirements are implemented; no meaningful simplification concerns were found.

Agents run: code-reviewer, error-auditor, test-reviewer, completeness-checker, simplifier


Reviewed by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Review Assessment

Review comment

Classifications

Finding Classification Reasoning
1. Single large unprojected response can exceed the stdout queue cap genuine Factual: While backpressured, every write is enqueued and the cap compares total queued bytes including the current frame. One complete snapshot response larger than 16 MiB therefore triggers fatal exit even with no prior queued backlog; snapshots serialize the full transcript as one unprojected JSONL frame. Scope: The cap and fatal path are introduced by this PR, while preserving complete transcript recovery through get_dashboard_snapshot is an explicit requirement. Killing the child while serving that response is a scoped correctness regression.
2. flushRawStdout can wait indefinitely below the cap deferred Factual: Its waiter resolves only after a full drain, has no timeout, and no further cap check occurs after writes stop. Scope: The only caller is print mode; the issue's RPC/dashboard path does not call it, and the old flush callback had comparable waiting semantics. This is optional hardening for a separate print-mode shutdown edge case.

Action Plan

  1. Make the 16 MiB limit bound accumulated backlog rather than reject a single legitimate oversized frame, while preserving ordering and bounded behavior for subsequent queued writes. Add regressions proving one oversized frame drains without exit and accumulated multi-frame backlog still fails loudly.

Deferred Follow-up

  • Consider a bounded wait or explicit failure policy for flushRawStdout when a quiet, below-cap print-mode pipe never drains.

Assessment by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Progress Update

Addressed genuine review finding 1:

  • Changed the 16 MiB stdout limit to bound accumulated ordinary backlog without rejecting one legitimate oversized protocol frame, such as a complete dashboard snapshot.
  • Preserved ordering and loud failure for subsequent writes or ordinary multi-frame backlog beyond the cap.
  • Added regression coverage proving a frame larger than 16 MiB drains without exiting; existing cap tests continue to prove accumulated backlog fails loudly.

Verification passed: Biome, focused output-guard tests, full monorepo build, full test suite, workspace-link verification, diff checks, and commit hooks (5,586 passed, 0 failed).

Commit: 77a3996


Progress tracked by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Code Review

Critical

None.

Important

None.

Suggestions

  1. Exercise high-rate RPC output through real stdout backpressure (packages/coding-agent/test/rpc-mode-dashboard-projection.test.ts, confidence 95). The long-stream tests spy on writeRawStdout, while output-guard tests use only small hand-written chunks, so the composed streaming/queue/drain behavior is not directly covered.

  2. Test the write following an allowed oversized frame (packages/coding-agent/test/output-guard.test.ts, confidence 98). Existing tests prove one oversized frame is allowed and ordinary aggregate backlog fails, but do not prove that a small write queued behind an already oversized frame triggers the cap.

  3. Bound flushRawStdout waiting on a permanently stalled below-cap pipe (packages/coding-agent/src/core/output-guard.ts, confidence 85). Its waiter resolves only on drain; with no further writes and no drain, a print-mode caller can wait indefinitely without a diagnostic.

  4. Deduplicate repeated cap-overflow fatal handling (packages/coding-agent/src/core/output-guard.ts, confidence 88). The exit guard is local to each overflow invocation, so a synchronous burst after the first breach can emit repeated diagnostics and arm multiple force-exit timers.

  5. Handle stdout stream errors during asynchronous drain flushing (packages/coding-agent/src/core/output-guard.ts, confidence 80). A severed pipe can emit an unhandled EPIPE while queued writes flush, producing an uncaught exception rather than the queue's actionable fatal diagnostic.

  6. Avoid a redundant hot-path shallow copy (packages/coding-agent/src/modes/rpc/rpc-event-projection.ts, confidence 92). omit(event, "message") already creates a fresh object; assigning the projected assistantMessageEvent to that copy avoids spreading it into a second object for every token delta.

Strengths

  • Dashboard projection is narrowly gated, immutable, recursive for background-agent events, and preserves complete final/snapshot paths and generic RPC compatibility.
  • Queue ordering, repeated backpressure, takeover routing, nonduplication, cap diagnostics, forced-exit behavior, and the single-oversized-frame policy are substantively tested.
  • High-rate tests establish bounded projected frames and near-linear aggregate serialized bytes.
  • All issue acceptance criteria and approved plan deliverables are implemented and documented.

Agents run: code-reviewer, error-auditor, test-reviewer, completeness-checker, simplifier


Reviewed by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Review Assessment

Review comment

Classifications

Finding Classification Reasoning
1. High-rate RPC test does not compose with real backpressure nitpick Factual: The streaming test replaces writeRawStdout, so no single test composes the long projected stream with the real queue. Scope: Projection/frame bounds and the content-agnostic queue are independently tested; composing them exercises no additional branch required by the acceptance criteria.
2. No regression for a write following an allowed oversized frame genuine Factual: Existing tests allow one oversized frame and separately test ordinary accumulated backlog, but never exercise the next-write branch after the carve-out. Scope: This new carve-out preserves complete snapshot recovery while its next-write check is the safety boundary preventing unbounded growth; mandatory cap behavior should cover it.
3. flushRawStdout can wait indefinitely below the cap deferred Factual: Its waiter resolves only on drain, with no timeout. Scope: Only print mode calls it; the scoped RPC/dashboard path does not. This is separate print-mode shutdown hardening.
4. Repeated overflow calls duplicate diagnostics and timers nitpick Factual: Each invocation creates an independent local exit guard and timer. Scope: The first exit wins, timers are unref'd, and duplicate diagnostics are cosmetic; loud failure remains correct.
5. EPIPE during asynchronous drain flushing is unhandled deferred Factual: Output writes have no error callback/listener, so a severed pipe can surface as an uncaught exception. Scope: This is a pre-existing repository-wide stdout exposure, not a regression introduced by the scoped change.
6. Redundant second shallow copy in projection nitpick Factual: omit already returns a fresh object before the second spread. Scope: This small allocation does not affect correctness or near-linear serialized bytes; it is a micro-optimization.

Action Plan

  1. Add an output-guard regression that enters backpressure, queues one frame larger than MAX_QUEUED_STDOUT_BYTES without failure, then queues a small second write and asserts the fatal diagnostic and exit path.

Deferred Follow-up

  • Consider a tracking issue for a bounded/loud flushRawStdout timeout in print mode.
  • Consider a tracking issue for repository-wide stdout EPIPE handling.

Assessment by mach6

@m-aebrer

Copy link
Copy Markdown
Collaborator Author

Progress Update

Addressed genuine review finding 2:

  • Added a regression proving one oversized queued protocol frame remains allowed during backpressure.
  • Verified that a subsequent queued write crosses the accumulated-backlog boundary and triggers the fatal queue-cap diagnostic and exit path.
  • Verification passed: Biome, focused output-guard tests, full monorepo build, full test suite, workspace-link verification, diff checks, and commit hooks (5,587 passed, 0 failed).

Commit: f2bf396


Progress tracked by mach6

@m-aebrer
m-aebrer merged commit 80dc843 into master Aug 11, 2026
3 checks passed
@m-aebrer
m-aebrer deleted the feature/issue-448-bound-rpc-runtime-events branch August 11, 2026 20:44
Hrovatin pushed a commit to Hrovatin/dreb that referenced this pull request Aug 13, 2026
* chore: open PR for issue 448

* Bound dashboard runtime events before RPC serialization

* Fix stdout backpressure review findings

* Fix oversized stdout frames

* Fix oversized frame queue cap regression

* chore: bump version to 2.55.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bound dashboard runtime events before RPC serialization

1 participant